(function ($,window) {
    //1.表头数据
    window.titles=''
    window.current_col = 2//当前排序列下标
    window.current_desc = {}//记录是否点了两下，当前是否降序
    //母表数据（ajax返回结果,需排序）
    window.rowData = null;//格式：[['QSR','Total','1000','50'],[]]
    //子表数据（ajax返回结果,需排序）
    window.subRowData = null;
    window.tooltip_title = null;
    window.tag=null;
    window.expandCallBack=null;
    //tbl_ele :table对象
    //sortTitle:默认排序标题
    //tooltip true/false
    $.fn.buildTables=function(options) {
        var defaults = {
            "titles":["A","B","C"],
            "rowData":[['QSR1','Total1','100'],['QSR2','Total2','1000'],['QSR3','Total3','10']],
            "subRowData":[],
            "sortTitle":"C",
            "desc":1,
            "tooltip":false,
            "tooltip_title":"tooltip",
            "association_col":1 , //子表与父表关联的列  0：父表数据第一列，1：父表数据第二列
            "child_first_space":true ,//子表第一列是否空行
            "scroll_title":true,//滚动时标题是否固定
        };
        var settings = $.extend(defaults, options);
        var tbl_ele=this;
        var option = {};
        option.titles=''
        option.current_col = 2//当前排序列下标
        option.current_desc = {}//记录是否点了两下，当前是否降序
        option.titles=settings.titles;
        option.rowData=settings.rowData;
        option.subRowData=settings.subRowData;
        option.tooltip_title=settings.tooltip_title;
        option.tag=tbl_ele[0].id
        var sortTitle=settings.sortTitle;
        var desc=settings.desc;
        var tooltip=settings.tooltip;
        var tooltip_title=settings.tooltip_title;
        var association_col=settings.association_col;
        var child_first_space=settings.child_first_space;
        var sortData = _parentTabSort(sortTitle, desc, option)
        option.expandCallBack=settings.expandCallBack;
        _buildTableByAjaxData(tbl_ele, sortData, tooltip,association_col,child_first_space,settings.scroll_title ,option)
    }

    //根据列名对母表排序(desc:1,降序，0升序)
    var _parentTabSort=function(sort_col_name, desc ,option) {
        //rowData;//格式：[['QSR','Total','1000','50'],[]]
        //current_col=2//当前排序列下标
        var rowData = option.rowData
        var idx = option.titles.indexOf(sort_col_name)
        if (idx == -1) {
            alert("未找到要排序的列！  " + sort_col_name)
        } else {
            current_col = idx;
        }
        //暂时使用冒泡排序
        for (var rowi = 0; rowi < rowData.length - 1; rowi++) {
            for (var rowj = rowi + 1; rowj < rowData.length; rowj++) {
                var sortNum1 = rowData[rowi][option.current_col].replace(",", "")
                sortNum1 = new Number(sortNum1)
                var sortNum2 = rowData[rowj][option.current_col].replace(",", "")
                sortNum2 = new Number(sortNum2)
                if (desc == 1 && sortNum2 > sortNum1) {//降序
                    var temp = rowData[rowi];
                    rowData[rowi] = rowData[rowj]
                    rowData[rowj] = temp
                }
                if (desc == 0 && sortNum2 < sortNum1) {//升序
                    var temp = rowData[rowi];
                    rowData[rowi] = rowData[rowj]
                    rowData[rowj] = temp
                }
            }
        }
        return rowData
    }

    //根据列名对子表排序（根据母表的当前升降序排序）
    var _subTabSort=function(rowData,option) {
        //rowData;//格式：[['QSR','Total','1000','50'],[]]
        //current_col=1//当前排序列下标
        //获取母表的当前升降序
        var desc = 1
        for (var cur in option.current_desc) {
            if (cur == option.titles[option.current_col]) {
                desc = option.current_desc[cur]
            }
        }
        var current_col = option.current_col - 1
        //暂时使用冒泡排序
        for (var rowi = 0; rowi < rowData.length - 1; rowi++) {
            for (var rowj = rowi + 1; rowj < rowData.length; rowj++) {
                var sortNum1 = rowData[rowi][current_col].replace(",", "")
                sortNum1 = new Number(sortNum1)
                var sortNum2 = rowData[rowj][current_col].replace(",", "")
                sortNum2 = new Number(sortNum2)
                if (desc == 1 && sortNum2 > sortNum1) {//降序
                    var temp = rowData[rowi];
                    rowData[rowi] = rowData[rowj]
                    rowData[rowj] = temp
                }
                if (desc == 0 && sortNum2 < sortNum1) {//升序
                    var temp = rowData[rowi];
                    rowData[rowi] = rowData[rowj]
                    rowData[rowj] = temp
                }
            }
        }
        return rowData
    }

    var _buildTable1=function(index, $el, cells, rowData2, tooltip,child_first_space,option) {
        cells = child_first_space?cells - 1:cells;
        var i, j, row,
            columns = [],
            data = [];

        for (i = 0; i < cells; i++) {
            columns.push({
                field: 'field' + i,
                //title: title2[i],
                sortable: false
            });
        }

        for (i = 0; i < rowData2.length; i++) {
            row = {};
            for (j = 0; j < cells; j++) {
                row['field' + j] = rowData2[i][j];
            }
            data.push(row);
        }
        //修改为与母表对齐
        var detail_tr = $el.parent()
        detail_tr.empty()
        var rows = ""
        for (var k = 0; k < data.length; k++) {//一个数据一行
            var row = ""
            if(child_first_space){
                row = "<tr class='detail_" + index + "'><td></td><td style></td>"
            }else{
                row = "<tr class='detail_" + index + "'><td></td>"
            }
            var first_run = true
            for (var key in data[k]) {
                if (first_run) {//加入Tooltip 浮窗
                    row = row + "<td style>" + _getTooltipHtml("3_" + data[k][key], tooltip,option) + "</td>"
                    first_run = false
                } else {
                    row = row + "<td style>" + data[k][key] + "</td>"
                }
            }
            rows = rows + row + "</tr>"
        }
        detail_tr.after(rows)
    }


    var _buildTableByAjaxData=function(tbl_ele, sortData, tooltip,association_col,child_first_space,scroll_title,option) {
        var columns = []
        for (var i = 0; i < option.titles.length; i++) {
            columns.push({
                field: 'field' + i,
                title: option.titles[i],
                sortable: false,
            });
        }
        //2.母表 数据
        var data = [];
        for (var i = 0; i < sortData.length; i++) {
            row = {};
            for (var j = 0; j < option.titles.length; j++) {
                row['field' + j] = sortData[i][j];
            }
            data.push(row);
        }
        var clear_table = "<table data-detail-view=\"true\" id=\"compareplatform_"+option.tag+"\" ></table>"
        tbl_ele.empty()
        tbl_ele.append(clear_table)
        var $table = $('#compareplatform_'+option.tag);
        $table.bootstrapTable({
            columns: columns,
            data: data,
            detailView: option.titles.length > 1,
            onExpandRow: function (index, row, $detail) {
                //设置背景高亮
                var detail_tr = $detail.parent()
                var parent_tr = detail_tr.prev()
                parent_tr.css({
                    "background": "#fff3f5"
                })
                var cate_name = row['field'+association_col]

                //子表 数据
                var subRow = option.subRowData[cate_name]
                _expandTable(index, $detail, option.titles.length, subRow, tooltip,child_first_space ,option);
                //设置表格的列 无边框
                _initTableStyleCategory(option);
                if(option.expandCallBack==null){
                }else{
                    option.expandCallBack(index,row);
                }
            },
            onCollapseRow: function (index, row) {
                //设置品类行背景高亮
                var detail_tr = $(".detail_" + index)
                var parent_tr = detail_tr.prev().prev()
                parent_tr.css({
                    "background": "#ffffff"
                })
                $(".detail_" + index).remove()
            },
        });
        //表头居中
        $("div.th-inner ").css({
            "text-align": "center",
            "cursor": "pointer"
        })
        //查看过去十二个月的趋势
        for (var i = 0; i < data.length; i++) {
            var cate_td = $("#compareplatform_"+option.tag+" tbody tr[data-index='" + i + "'] td:nth-child(2)")
            var td_html = _getTooltipHtml("1_" + cate_td.text(), tooltip,option)//加入Tooltip 浮窗
            cate_td.empty()
            cate_td.append(td_html)
            var sub_cate_td = $("#compareplatform_"+option.tag+" tbody tr[data-index='" + i + "'] td:nth-child(3)")
            var td_html2 = _getTooltipHtml("2_" + sub_cate_td.text(), tooltip,option)
            sub_cate_td.empty()
            sub_cate_td.append(td_html2)
        }
        $(".cate_tooltip").tooltip();
        //设置表格的列 无边框
        _initTableStyleCategory(option);
        //点击表头排序，更新表格
        $(".th-inner ").on("click", function () {
            var title = $(this).text()
            var idx = option.titles.indexOf(title)
            if (idx != 0 && idx != 1) {//1,2列不排序
                //其他col标志清零
                for (var key in option.current_desc) {
                    if (title != key) {
                        option.current_desc[key] = 0
                    }
                }
                if (option.current_desc[title] == null || option.current_desc[title] == 0) {//当前升序
                    option.current_desc[title] = 1
                } else {
                    option.current_desc[title] = 0
                }
                var sortData = _parentTabSort(title, option.current_desc[title],option)
                _buildTableByAjaxData(tbl_ele, sortData, tooltip,association_col,child_first_space,option)
                //排序表头选中列样式
                var cli = $("th[data-field=field" + idx + "]");
                cli.css({
                    "color": "#6a6c6f",
                })
            }
        })
        //滚动时固定表头
        if(scroll_title) {
            $("#compareplatform_" + option.tag + " thead tr th").css("position", "relative").css("top", "0px");//设置相对定位
            tbl_ele.on('scroll', function () {
                var top = tbl_ele.scrollTop();
                if (top > 0) {
                    $("#compareplatform_" + option.tag).css("margin-top", "-1px");//覆盖上面的间隙
                } else {
                    $("#compareplatform_" + option.tag).css("margin-top", "0px");
                }
                $('#compareplatform_' + option.tag + ' thead tr th').css({
                    "top": top + "px",
                    "background": "#fff",
                    "color": "#6a6c6f",
                    "border-bottom": "3px solid #ba1b20"
                })
                //排序表头选中列样式
                var cli = $("th[data-field=field" + option.current_col + "]");
                cli.css({
                    "color": "#6a6c6f",
                })
            });
        }

        //默认排序表头选中列样式
        var cli = $("th[data-field=field2]");
        cli.css({
            "color": "#6a6c6f",
        })
    }

    //设置表格的列 无边框initTableStyle
    var _initTableStyleCategory=function(option) {
        $('#compareplatform_'+option.tag+' thead').css({
            //"background": "#ba1b20",
            //"color": "#ffffff"
            "border-bottom": "3px solid #ba1b20"
        })
        $('#compareplatform_'+option.tag).css({
            "border-left": "none",
            "border-right": "none"
        });
        $('#compareplatform_'+option.tag+' tr td').css({
            "border-left": "none",
            "border-right": "none"
        });
        $('#compareplatform_'+option.tag+' tr th').css({
            "border-left": "none",
            "border-right": "none"
        });
        $('#compareplatform_'+option.tag).attr("style", "overflow-y:scroll;height:145px")

    }

    var _expandTable=function(index, $detail, cells, subRow, tooltip,child_first_space,option) {
        //子表排序
        var subRow = _subTabSort(subRow,option)
        _buildTable1(index, $detail, cells, subRow, tooltip,child_first_space,option);
    }

    //提示
    var _getTooltipHtml=function(args, need_tip,option) {
        if (need_tip == false && args.split("_")[0] == 1) {
            var html = "<a href=\"javascript:void(0)\" class=\"cate_tooltip\" style='color:#cf3138;font-weight:bold;'" +
                ">" + args.split("_")[1] + "</a>"
            return html
        }
        if (need_tip == false && args.split("_")[0] == 2) {
            var html = "<a href=\"javascript:void(0)\" class=\"cate_tooltip\" style='color:#cf3138;font-weight:bold;'" +
                ">" + args.split("_")[1] + "</a>"
            return html
        }
        if (need_tip == false && args.split("_")[0] == 3) {
            var html = "<a href=\"javascript:void(0)\" class=\"cate_tooltip\" style='color:#6a6c6f;font-weight:bold;'" +
                ">" + args.split("_")[1] + "</a>"
            return html
        }
        if (args.split("_")[0] == 1 || args.split("_")[0] == 2) {
            var html = "<a href=\"javascript:void(0)\" class=\"cate_tooltip\" style='color:#cf3138;font-weight:bold;'" +
                "data-toggle=\"tooltip\" " +
                "title=" +option.tooltip_title +
                " onclick='showLastData(\"" + args + "\")'>" + args.split("_")[1] + "</a>"
            return html
        } else {
            var html = "<a href=\"javascript:void(0)\" class=\"cate_tooltip\" style='font-weight:bold;color:#6a6c6f'" +
                "data-toggle=\"tooltip\" " +
                "title=" +option.tooltip_title +
                " onclick='showLastData(\"" + args + "\")'>" + args.split("_")[1] + "</a>"
            return html
        }
    }
})(jQuery,window);